/**
 * Copyright (C)  2011  chen wei hua.
 * Permission is granted to copy, distribute and/or modify this document
 * under the terms of the GNU Free Documentation License, Version 2.0
 * or any later version published by the Free Software Foundation;
 * with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts.
 * A copy of the license is included in the section entitled "GNU Free Documentation License".
 */
package com.javaeye.chenweihuacwh.dao.orderManage;

import java.sql.SQLException;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.criterion.CriteriaSpecification;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.javaeye.chenweihuacwh.dto.DTO;
import com.javaeye.chenweihuacwh.dto.orderManage.CustomerOrder;
import com.javaeye.chenweihuacwh.service.orderManage.IOrderService;
import com.javaeye.chenweihuacwh.web.PageInfo;
import com.javaeye.chenweihuacwh.web.orderManage.OrderCondition;

public class OrderDAOHibernate extends HibernateDaoSupport implements OrderDAO {
	
	@SuppressWarnings("unchecked")
	public int getMaxOrderId(String orderId) {
		final String queryString = "select max(co.id) from CustomerOrder co where co.id like '" + orderId + "%'";
		List result = getHibernateTemplate().find(queryString);
		if (result.get(0) == null) {
			return 0;
		}
		String maxId = result.get(0).toString();
		maxId = maxId.replace(orderId, "").replace("-", "");
		return Integer.parseInt(maxId);
	}
	
	@Override
	public void saveOrder(CustomerOrder order) {
		getHibernateTemplate().saveOrUpdate(order);
	}
	
	public CustomerOrder getOrderBaseInfo(String orderId) {
		return (CustomerOrder)getHibernateTemplate().get(CustomerOrder.class, orderId);
	}
	
	@SuppressWarnings("unchecked")
	public long getOrderByOrderStatus(int status) {
		final String queryString = "select count(co.id) from CustomerOrder co where co.status = ?";
		List result = getHibernateTemplate().find(queryString, status);
		long value = 0;
		if (result != null && result.get(0) != null) {
			value = (Long)result.get(0);
		}
		return value;
	}
	
	@SuppressWarnings("unchecked")
	public List getPageData(final DTO contidions, final PageInfo pageInfo) {
		HibernateCallback action = new HibernateCallback() {
			@Override
			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
				
				int pageIndex = pageInfo.getPageIndex();
				int pageSize = pageInfo.getPageSize();
				OrderCondition contidion = (OrderCondition)contidions;
				Criteria crit = session.createCriteria(CustomerOrder.class);
				/*
				if (OrderCondition.DATE_TYPE_CURRENT_MONTH==contidion.getCreateDateType()) {
					crit.add(Restrictions.between("createDate", 
							DateUtils.getCurrentMonthBeginDate(), DateUtils.getCurrentMonthEndDate()));
				} else if (OrderCondition.DATE_TYPE_PRE_MONTH==contidion.getCreateDateType()) {
					crit.add(Restrictions.between("createDate", 
							DateUtils.getBeforeMonthBeginDate(), DateUtils.getBeforeMonthEndDate()));
				} else if (OrderCondition.DATE_TYPE_WARN==contidion.getCreateDateType()) {
					//查询已经业务确认，还未出货的，五天后预计要出货的单子
					crit.add(Restrictions.between("status", IOrderService.ORDER_STATES_BUSINESS, IOrderService.ORDER_STATES_CHECKED));
					crit.add(Restrictions.le("expectOutDate", DateUtils.getDateFromNow(5)));//le是<=, ge是>=
				}
				*/
				if (!"".equals(contidion.getCustomName().trim())) {
					crit.add(Restrictions.like("customName", "%" + contidion.getCustomName().trim() + "%"));
				}
				
				Object[] status = contidion.getStatus();
				if (status != null && status.length > 0) {
					if ((Integer)status[0] != IOrderService.ORDER_STATES_CLOSED) {
						crit.add(Restrictions.in("status", status));
					}
				}
				if (!"".equals(contidion.getProductName().trim())) {
					crit.createAlias("orderDetails", "d")
					.add(Restrictions.like("d.productName", "%" + contidion.getProductName().trim() + "%"));
				}
				//未结束
				crit.add(Restrictions.between("status", IOrderService.ORDER_STATES_CREATED, IOrderService.ORDER_STATES_END - 1));
				//按照创建日期倒序排序
				crit.addOrder(Order.desc("id"));
				
				crit.setProjection(Projections.rowCount());
				Integer rowNumber = (Integer)crit.uniqueResult();
				pageInfo.setCount(rowNumber);
				
				crit.setProjection(null);//取得了总数后,为了能够再次取得对象列表
				crit.setResultTransformer(CriteriaSpecification.ROOT_ENTITY);//当hibernate采用关联的时候不使用这个返回的是个对象数组，加上这个返回的是当前列表的对象。
				crit.setFirstResult(pageIndex * pageSize);
				crit.setMaxResults(pageSize);
				return crit.list();
			}
		};
		return getHibernateTemplate().executeFind(action);
	}

}
